import React,{useEffect,useState,useRef} from 'react'
import { useSearchParams,useNavigate } from 'react-router-dom'
import { _getPlayListDetail }from '../../api/recommend'
import { Toast,Flex,Sticky} from 'react-vant';
import { changeTimeFormat,tranNumber } from '../../utils/index'
import {connect} from 'react-redux';
import {changeMusicSrcAsync,changeMusicCurrentDetail,changeMusicList} from '../../store/actions/music'
import {NavBarRanking } from '../../components/NavBar/NavBarRanking/index'
import './index.scss'
function SongListDetails(props) {
    const navigate = useNavigate()
    const [search] = useSearchParams()
    const [songListDetailsList, setSongListDetailsList] = useState({})
    const [imgBgcolor, setImgBgcolor] = useState('#eee')
    const [navBarBgColor,setNavBarBgColor] =useState('eee')
    const [play,setPlay] =useState(false)
    const canvas = useRef(null)
    const imgDom = useRef(null)
    function getImgColor(url) {
        const img = new Image()
        img.crossOrigin = ''
        img.src = url
        const ctx = canvas.current.getContext('2d')
        img.onload = function() {
            ctx.drawImage(img,0,0,150,150)
            let imgData = (ctx.getImageData(0, 0, img.width, img.height)).data
            const a = '(' + imgData[0] + ',' + imgData[1] + ',' + imgData[2] + ')'
            const b = '(' + imgData[0] + ',' + imgData[1] + ',' + imgData[2] + ',0.8'+ ')'
            setImgBgcolor(`rgba${b}`)
            setNavBarBgColor(`rgb${a}`)
        }
    }
    function goPlaySong(item){
        props.changeMusicList(songListDetailsList.tracks)
        props.changeMusicSrcAsync(item.id)
        props.changeMusicCurrentDetail(item)
        let timer = setInterval(() => {
            props.musicNode.oncanplay=()=>{
                props.musicNode.play()
              clearInterval(timer)
              navigate('/playsong')
            }
          }, 10); 
    }
    function playAllsong(){
        let flag = play
        setPlay(!flag)
        props.changeMusicList(songListDetailsList.tracks)
        props.changeMusicSrcAsync(songListDetailsList.tracks[0].id)
        props.changeMusicCurrentDetail(songListDetailsList.tracks[0])
        let timer = setInterval(() => {
            props.musicNode.oncanplay=()=>{
                props.musicNode.play()
              clearInterval(timer)
              navigate('/playsong')
            }
          }, 10); 
        console.log('--');
    }
    useEffect(() => {
        _getPlayListDetail(search.get('id')).then(res=>{
            setSongListDetailsList(res.playlist)
            getImgColor(res.playlist.coverImgUrl+'?param=150y150')
        }).catch(err => { Toast.info(err.msg || err.message || '网络错误，请稍后再试') })
    }, [])
    return (
        <div className='song_list_details'>
            <canvas ref={canvas} style={{display: 'none'}}></canvas>
            <NavBarRanking navBarBgColor={navBarBgColor}/>
            { songListDetailsList.coverImgUrl && <Flex className='song_list_details_top' style={{background: imgBgcolor}}>
                <div className='coverImg'>
                    <img ref={imgDom} src={songListDetailsList.coverImgUrl+'?param=150y150'} alt=""/>
                    <div>
                        <span className='iconfont icon-24gl-play'/>
                        {songListDetailsList.playCount?tranNumber(songListDetailsList.playCount,1):''}
                    </div>
                </div>
                <Flex direction='column' justify='between' className='song_list_details_top_content'>
                    <span>{songListDetailsList.name}</span>
                    <Flex direction='column' justify='around'>
                        <Flex align='center'>
                            <div className='avatar'>
                                <img src={songListDetailsList.creator.avatarUrl+'?param=50y50'} alt=""/>
                                <img src={songListDetailsList.creator.avatarDetail.identityIconUrl+'?param=50y50'} alt=""/>
                            </div>
                            <span className='nickname'>{ songListDetailsList.creator.nickname }</span>
                        </Flex>
                        <span className='update_time'>{changeTimeFormat(songListDetailsList.updateTime,'M-D')}</span>
                        <span className='description'>{songListDetailsList.description.length>10?songListDetailsList.description.slice(0,10)+'...' : songListDetailsList.description}</span>
                    </Flex>
                </Flex>
                <Flex className='cell'>
                    <div>
                        <span className='iconfont icon-zhengque'></span>
                        {songListDetailsList.subscribedCount?tranNumber(songListDetailsList.subscribedCount,1):'收藏'}
                    </div>
                    <div>
                        <span className='iconfont icon-pinglun-'></span>
                        {songListDetailsList.commentCount?tranNumber(songListDetailsList.commentCount,1):'评论'}
                    </div>
                    <div>
                        <span className='iconfont icon-fenxiang'></span>
                        {songListDetailsList.shareCount?tranNumber(songListDetailsList.shareCount,1):'分享'}
                    </div>
                </Flex>
            </Flex>}
            
            {songListDetailsList.tracks && <div className='song_list_details_main'>
                <Sticky offsetTop={50}>
                    <Flex align='center' className='song_list_details_main_title'>
                        <span className={['iconfont',play?'icon-bofanganniuxhdpi':'icon-24gf-playCircle'].join(' ')} onTouchStart={playAllsong}/>
                        <span>播放全部</span>
                        <span>({songListDetailsList.trackCount})</span>
                    </Flex>
                </Sticky> 
            
                <div className='song_list_details_main_list'>
                    {
                        songListDetailsList.tracks.map((item,index)=>{
                            return (
                                <Flex align='center' key={index} 
                                    className='song_list_details_main_list_item'
                                    onTouchStart={()=>goPlaySong(item)}
                                >
                                    <span>{index+1}</span>
                                    <div className='song_name'>
                                        <div>{item.name}</div>
                                        <div>{item.ar[0].name}</div>
                                    </div>
                                
                                </Flex>
                            )
                        })
                    }
            
                </div>
            </div>}
         
        </div>
    )
}

export default connect(
    state =>({
        musicNode:state.musicNode
    }),{
        changeMusicList,
        changeMusicSrcAsync,
        changeMusicCurrentDetail
    })(SongListDetails);